package com.dingyx.ps.filter;

import com.alibaba.fastjson.JSONArray;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.aspectj.lang.annotation.AfterReturning;

import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

@Aspect
@Component
/**
 * @author dingyuxin
 *
 */
@Slf4j
public class WebLogAspect {

    /**
     * 定义切入点，切入点为com.example.aop下的所有函数
     */
    @Pointcut("execution(public * com.dingyx.ps.controller..*.*(..))")
    public void webLog(){}

    /**
     * 前置通知：在连接点之前执行的通知
     * @param joinPoint
     * @throws Throwable
     */
    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        String methodName = joinPoint.getSignature().getName();
        String typeName = joinPoint.getSignature().getDeclaringType().getSimpleName();
        List<Object> args2Show = new ArrayList<>();
        for(Object arg : args){
            if(arg instanceof MultipartFile ||
                    arg instanceof HttpServletRequest || arg instanceof Valid){
                continue;
            }
            args2Show.add(arg);
        }
        log.info("请求类型:{} 请求地址:{}, 请求参数:{}", typeName, methodName, JSONArray.toJSONString(args2Show));
    }

    @AfterReturning(returning = "ret",pointcut = "webLog()")
    public void doAfterReturning(Object ret) throws Throwable {
        // 处理完请求，返回内容
        log.info("RESPONSE : " + ret);
    }
}